package com.liujit.upms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.enums.SqlKeyword;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liujit.common.constants.ColumnConstant;
import com.liujit.common.constants.GlobalConstant;
import com.liujit.common.domain.params.BaseParams;
import com.liujit.common.domain.result.PageBean;
import com.liujit.common.exception.DataNotFoundException;
import com.liujit.common.utils.CommonUtil;
import com.liujit.common.utils.DozerConvertor;
import com.liujit.common.utils.Pagination;
import com.liujit.upms.domain.model.SysPermission;
import com.liujit.upms.domain.model.SysRolePermission;
import com.liujit.upms.domain.params.SysPermissionParams;
import com.liujit.upms.domain.query.SysPermissionQuery;
import com.liujit.upms.domain.result.SysPermissionResult;
import com.liujit.upms.mapper.SysPermissionMapper;
import com.liujit.upms.service.SysMenuService;
import com.liujit.upms.service.SysPermissionService;
import com.liujit.upms.service.SysRolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 系统权限Service实现类
 * @Author liujun
 * @Date 2021-07-02 15:00:56
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission>
        implements SysPermissionService {

    private SysMenuService sysMenuService;

    private SysRolePermissionService sysRolePermissionService;

    @Autowired
    public void setSysMenuService(SysMenuService sysMenuService) {
        this.sysMenuService = sysMenuService;
    }

    @Autowired
    public void setSysRolePermissionService(SysRolePermissionService sysRolePermissionService) {
        this.sysRolePermissionService = sysRolePermissionService;
    }

    @Override
    public PageBean<SysPermissionResult> getPage(SysPermissionQuery query) {
        // 排序
        if (StrUtil.isNotBlank(query.getSortName()) && StrUtil.isNotBlank(query.getSortOrder())) {
            query.setSortName(ColumnConstant.CREATE_TIME);
            query.setSortOrder(SqlKeyword.DESC.getSqlSegment());
        }
        Page<SysPermission> page = Pagination.page(query);
        LambdaQueryWrapper<SysPermission> wrapper = new LambdaQueryWrapper();
        if (StrUtil.isNotBlank(query.getName())) {
            wrapper.like(SysPermission::getName, query.getName());
        }
        if (StrUtil.isNotBlank(query.getBtnPermission())) {
            wrapper.like(SysPermission::getBtnPermission, query.getBtnPermission());
        }
        if (query.getMenuId() != null) {
            wrapper.eq(SysPermission::getMenuId, query.getMenuId());
        }
        if (query.getEnabled() != null) {
            wrapper.eq(SysPermission::getEnabled, query.getEnabled());
        }
        if (query.getStartTime() != null) {
            wrapper.ge(SysPermission::getCreateTime, query.getStartTime());
        }
        if (query.getEndTime() != null) {
            wrapper.le(SysPermission::getCreateTime, query.getEndTime());
        }
        IPage<SysPermission> iPage = super.page(page, wrapper);
        return PageBean.page(iPage, SysPermissionResult.class);
    }

    @Override
    public Boolean save(SysPermissionParams params) {
        SysPermission entity = DozerConvertor.convertor(params, SysPermission.class);
        // 添加
        if (params.getId() == null) {
            entity.setEnabled(GlobalConstant.ENABLED_YES);
            Boolean res = super.save(entity);
            // 添加超级管理员按钮权限
            sysRolePermissionService.save(new SysRolePermission() {{
                setRoleId(Convert.toLong(GlobalConstant.SUPER_ROLE_ID));
                setPermissionId(entity.getId());
            }});
            return res;
        } else {
            SysPermission sysPermission = super.getById(params.getId());
            if (sysPermission == null) {
                throw new DataNotFoundException();
            }
            return super.updateById(entity);
        }
    }

    @Override
    public SysPermissionResult get(Long id) {
        SysPermission sysPermission = super.getById(id);
        if (sysPermission == null) {
            throw new DataNotFoundException();
        }
        return DozerConvertor.convertor(sysPermission, SysPermissionResult.class);
    }

    @Override
    public SysPermissionResult getDetail(Long id) {
        SysPermissionResult result = this.get(id);
        result.setMenuName(sysMenuService.getNameById(result.getMenuId()));
        return result;
    }

    @Override
    public Boolean del(BaseParams params) {
        SysPermission sysPermission = super.getById(params.getId());
        if (sysPermission == null) {
            throw new DataNotFoundException();
        }
        // 删除按钮权限
        LambdaQueryWrapper<SysRolePermission> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(SysRolePermission::getPermissionId, params.getId());
        sysRolePermissionService.remove(deleteWrapper);
        return super.removeById(params.getId());
    }

    @Override
    public Boolean enabled(BaseParams params) {
        SysPermission sysPermission = super.getById(params.getId());
        if (sysPermission == null) {
            throw new DataNotFoundException();
        }
        return super.updateById(new SysPermission() {{
            setId(params.getId());
            setEnabled(GlobalConstant.ENABLED_YES);
        }});
    }

    @Override
    public Boolean disabled(BaseParams params) {
        SysPermission sysPermission = super.getById(params.getId());
        if (sysPermission == null) {
            throw new DataNotFoundException();
        }
        return super.updateById(new SysPermission() {{
            setId(params.getId());
            setEnabled(GlobalConstant.ENABLED_NO);
        }});
    }

    @Override
    public List<String> getByUserId(Long userId, boolean superAdmin) {
        List<String> list;
        // 权限信息
        if (superAdmin) {
            LambdaQueryWrapper<SysPermission> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(SysPermission::getBtnPermission);
            wrapper.eq(SysPermission::getEnabled, GlobalConstant.ENABLED_YES);
            list = super.listObjs(wrapper, item -> Convert.toStr(item));
        } else {
            list = super.baseMapper.selByUserId(userId);
        }
        return list;
    }

    @Override
    public List<Long> getPermissionIdByRoleId(Long roleId) {
        LambdaQueryWrapper<SysRolePermission> wrapper = new LambdaQueryWrapper();
        wrapper.select(SysRolePermission::getPermissionId);
        wrapper.eq(SysRolePermission::getRoleId, roleId);
        return sysRolePermissionService.listObjs(wrapper, item -> Convert.toLong(item));
    }

    @Override
    public Boolean modifyRolePermission(Long roleId, List<Long> ids) {
        // 查询全部菜单
        LambdaQueryWrapper<SysPermission> wrapper = new LambdaQueryWrapper();
        wrapper.select(SysPermission::getId);
        wrapper.eq(SysPermission::getEnabled, GlobalConstant.ENABLED_YES);
        List<Long> permissionIds = super.listObjs(wrapper, item -> Convert.toLong(item));
        // 删除现有角色权限
        LambdaQueryWrapper<SysRolePermission> removeWrapper = new LambdaQueryWrapper();
        removeWrapper.eq(SysRolePermission::getRoleId, roleId);
        sysRolePermissionService.remove(removeWrapper);
        List<SysRolePermission> list = new ArrayList<>();
        ids.forEach(item -> {
            if (CollectionUtil.contains(permissionIds, item)) {
                list.add(new SysRolePermission() {{
                    setRoleId(roleId);
                    setPermissionId(item);
                }});
            }
        });
        // 添加
        return sysRolePermissionService.saveBatch(list);
    }

    @Override
    public List<Long> getRoleIdByUrlPermission(Long menuId, String urlPermission) {
        List<Long> roleIds = new ArrayList<>();
        // 查询按钮权限
        LambdaQueryWrapper<SysPermission> permissionWrapper = new LambdaQueryWrapper();
        permissionWrapper.select(SysPermission::getId, SysPermission::getUrlPermission);
        permissionWrapper.eq(SysPermission::getMenuId, menuId);
        permissionWrapper.eq(SysPermission::getEnabled, GlobalConstant.ENABLED_YES);
        // 查询全部权限
        List<SysPermission> sysPermissionList = super.list(permissionWrapper);
        // 当前菜单权限ID
        List<Long> permissionIds = new ArrayList<>();
        for (SysPermission sysPermission : sysPermissionList) {
            boolean check = CommonUtil.checkContains(sysPermission.getUrlPermission(), urlPermission);
            // 当前地址存在该菜单下
            if (check) {
                permissionIds.add(sysPermission.getId());
            }
        }
        if (CollectionUtil.isNotEmpty(permissionIds)) {
            // 根据权限id，查询角色id
            LambdaQueryWrapper<SysRolePermission> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(SysRolePermission::getRoleId);
            queryWrapper.in(SysRolePermission::getPermissionId, permissionIds);
            roleIds = sysRolePermissionService.listObjs(queryWrapper, item -> Convert.toLong(item));
        }
        return roleIds;
    }
}
